package org.dromara.oce.controller.notify;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bytedance.ads.model.Oauth2AdvertiserGetResponseDataListInner;
import com.bytedance.ads.model.UserInfoV2ResponseData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.oce.config.JuLiangConfig;
import org.dromara.oce.config.JuLiangProperties;
import org.dromara.oce.constant.PlatformJuLangConstants;
import org.dromara.oce.constant.RedisKeyUtils;
import org.dromara.oce.domain.OceAccount;
import org.dromara.oce.service.OceAccountService;
import org.dromara.oce.service.remote.OceanEngineThirdRemoteService;
import org.dromara.oce.utils.DateTimeUtil;
import org.slf4j.MDC;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.List;
import java.util.Optional;

/**
 * 巨量引擎回调通知
 *
 * @desc:
 * @author: hhl
 * @date：2025/1/9 17:09
 * @module 小程序接口
 */
@Validated
@SaIgnore
@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/juLiang")
public class JuliangNotifyController {

    private final JuLiangConfig juLiangConfig;
    private final OceanEngineThirdRemoteService oceanEngineThirdRemoteService;
    private final OceAccountService oceAccountService;

    /**
     * 巨量申请授权回调地址（自研投放系统）
     *
     * @param auth_code
     * @param state
     * @param appCode
     * @return
     */
    @GetMapping("/authCallback")
    public String authCallback(@RequestParam("auth_code") String auth_code, @RequestParam("state") String state, @RequestParam("appCode") String appCode) {
        MDC.put("appCode", appCode);
        JuLiangProperties juLiangProperties = juLiangConfig.getJuLiangConfigList().stream().filter(item -> item.getAppCode().equals(appCode)).findFirst().get();
        String key = RedisKeyUtils.getAccessTokenKey(PlatformJuLangConstants.JULIANG, juLiangProperties.getAppId());
        String ref = RedisKeyUtils.getRefreshTokenKey(PlatformJuLangConstants.JULIANG, juLiangProperties.getAppId());
        JSONObject json = new JSONObject();
        json.put("appid", juLiangProperties.getAppId());
        json.put("secret", juLiangProperties.getSecret());
        json.put("grant_type", "auth_code");
        json.put("auth_code", auth_code);
        log.info("《巨量》获取token当前请求参数，{}", JSONUtil.toJsonStr(json));
        String post = HttpUtil.post(juLiangConfig.getUrl() + "/open_api/oauth2/access_token/", JSONUtil.toJsonStr(json));
//        String post = "{\"code\":0,\"message\":\"OK\",\"request_id\":\"20240819161716E8C1A090B240328C2715\",\"data\":{\"access_token\":\"30cc2700b1a189530327c6a8678c64f69d59aff4\",\"advertiser_ids\":[1667289310062595,1781236620734532],\"expires_in\":86399,\"refresh_token\":\"da99256d03d538bd75a3d98f8bdc305877b1c22a\",\"refresh_token_expires_in\":2591999}}";
        log.info("《巨量》获取token当前响应，{}", post);
        // 解析响应
        JSONObject resultObject = JSONObject.parseObject(post);
        JSONObject data = resultObject.getJSONObject("data");
        String accessToken = data.getString("access_token");
        String refreshToken = data.getString("refresh_token");
        RedisUtils.setCacheObject(key, accessToken, Duration.ofSeconds(data.getLong("expires_in") - 200L));
        RedisUtils.setCacheObject(ref, refreshToken, Duration.ofSeconds(data.getLong("refresh_token_expires_in") - 200L));
        return "success";
    }

    /**
     * 巨量申请授权回调地址（提供第三方服务）
     *
     * @param auth_code
     * @param state
     * @return https://open.oceanengine.com/audit/oauth.html?app_id=1833348663535772&state=1833348663535772&material_auth=1&redirect_uri=https://api-oceanengine.daishubobo.com/juLiang/account/authCallback
     * https://open.oceanengine.com/audit/oauth.html?app_id=1833348663535772&state=1833348663535772&material_auth=1&redirect_uri=http://gb68d99f.natappfree.cc/juLiang/account/authCallback
     */
    @GetMapping("/account/authCallback")
    public String authCallback2(@RequestParam("auth_code") String auth_code, @RequestParam("state") String state) {//1681579668960271   1667289310062595  1796771657030676   1833171623684105
        JuLiangProperties juLiangProperties = juLiangConfig.getJuLiangConfigList().stream().filter(item -> item.getAppId().equals(state)).findFirst().get();
        if (juLiangProperties == null) {
            return "fail";
        }
        MDC.put("appCode", juLiangProperties.getAppCode());
        JSONObject json = new JSONObject();
        json.put("appid", juLiangProperties.getAppId());
        json.put("secret", juLiangProperties.getSecret());
        json.put("grant_type", "auth_code");
        json.put("auth_code", auth_code);
        log.info("《巨量》获取token当前请求参数，{}", JSONUtil.toJsonStr(json));
        String post = HttpUtil.post(juLiangConfig.getUrl() + "/open_api/oauth2/access_token/", JSONUtil.toJsonStr(json));
//        String post = "{\"code\":0,\"message\":\"OK\",\"request_id\":\"20240819161716E8C1A090B240328C2715\",\"data\":{\"access_token\":\"30cc2700b1a189530327c6a8678c64f69d59aff4\",\"advertiser_ids\":[1667289310062595,1781236620734532],\"expires_in\":86399,\"refresh_token\":\"da99256d03d538bd75a3d98f8bdc305877b1c22a\",\"refresh_token_expires_in\":2591999}}";
        log.info("《巨量》获取token当前响应，{}", post);
        // 解析响应
        JSONObject resultObject = JSONObject.parseObject(post);
        JSONObject data = resultObject.getJSONObject("data");
        String accessToken = data.getString("access_token");
        String refreshToken = data.getString("refresh_token");
        JSONArray jsonArray = data.getJSONArray("advertiser_ids");
        long timeStamp = System.currentTimeMillis() / 1000;
        for (Object o : jsonArray) {
            String account = o.toString();
            String key = RedisKeyUtils.getAccountAccessTokenKey(PlatformJuLangConstants.JULIANG, account);
            String ref = RedisKeyUtils.getAccountRefreshTokenKey(PlatformJuLangConstants.JULIANG, account);
            RedisUtils.setCacheObject(key, accessToken, Duration.ofSeconds(data.getLong("expires_in") - 200L));
            RedisUtils.setCacheObject(ref, refreshToken, Duration.ofSeconds(data.getLong("refresh_token_expires_in") - 200L));

            OceAccount oceAccount = new OceAccount();
            List<Oauth2AdvertiserGetResponseDataListInner> oauth2Advertiser = oceanEngineThirdRemoteService.getOauthAdvertiser(account);
            if (oauth2Advertiser != null && oauth2Advertiser.size() > 0) {
                Optional<Oauth2AdvertiserGetResponseDataListInner> first = oauth2Advertiser.stream().filter(item -> item.getAdvertiserId() == Long.parseLong(account)).findFirst();
                Oauth2AdvertiserGetResponseDataListInner advertiserInfo = first.get();
                oceAccount.setAccessTokenExpires(data.getInteger("expires_in"));
                oceAccount.setRefreshTokenExpires(data.getInteger("refresh_token_expires_in"));
                oceAccount.setAccessTokenExpiresTime(DateTimeUtil.parseLocalDateTimeSecond(timeStamp + data.getLong("expires_in")));
                oceAccount.setRefreshTokenExpiresTime(DateTimeUtil.parseLocalDateTimeSecond(timeStamp + data.getLong("refresh_token_expires_in")));

                oceAccount.setAccountRole(advertiserInfo.getAccountRole());
                oceAccount.setAccountId(advertiserInfo.getAdvertiserId());
                oceAccount.setAccountName(advertiserInfo.getAdvertiserName());
                oceAccount.setValidStatus(advertiserInfo.getIsValid() ? 1 : 0);
            }

            UserInfoV2ResponseData oauthUserInfo = oceanEngineThirdRemoteService.getOauthUserInfo(account);
            if (oauthUserInfo != null) {
                oceAccount.setDisplayName(oauthUserInfo.getDisplayName());
                oceAccount.setEmail(oauthUserInfo.getEmail());
                oceAccount.setUserId(oauthUserInfo.getId());
                oceAccount.setAppId(oauthUserInfo.getAppId() + "");
                oceAccount.setMaterialAuthStatus(oauthUserInfo.getMaterialAuthStatus() ? 1 : 0);
            }
            oceAccountService.saveOrUpdate(oceAccount);
        }
        return "success";
    }


    public static void main(String[] args) {
        String post = "{\"code\":0,\"message\":\"OK\",\"request_id\":\"2025052914092807208A86B4F7C54D411B\",\"data\":{\"access_token\":\"facb83077bf95c2ffba49848fffae3edead51ded\",\"advertiser_ids\":[1681579668960271],\"expires_in\":86400,\"refresh_token\":\"58ee87320bcefbed21c8af4f33491b28fb1e3f7d\",\"refresh_token_expires_in\":2592000}}";
        JSONObject resultObject = JSONObject.parseObject(post);
        JSONObject data = resultObject.getJSONObject("data");
        String accessToken = data.getString("access_token");
        String refreshToken = data.getString("refresh_token");
        JSONArray jsonArray = data.getJSONArray("advertiser_ids");
        for (Object o : jsonArray) {
            String account = o.toString();
            String key = RedisKeyUtils.getAccountAccessTokenKey(PlatformJuLangConstants.JULIANG, account);
            String ref = RedisKeyUtils.getAccountRefreshTokenKey(PlatformJuLangConstants.JULIANG, account);
//            RedisUtils.setCacheObject(key, accessToken, Duration.ofSeconds(data.getLong("expires_in") - 200L));
//            RedisUtils.setCacheObject(ref, refreshToken, Duration.ofSeconds(data.getLong("refresh_token_expires_in") - 200L));
        }
        System.out.println(1);

    }

}
